package com.game.core.res
{
	import br.com.stimuli.loading.BulkLoader;
	
	import flash.utils.ByteArray;
	
	import utils.ByteArrayUtil;

	public class ResourceParser
	{
		public static function getXML(res : GameResource):XML
		{
			var content : *;
			if(res.getType() == BulkLoader.TYPE_BINARY)
			{
				try
				{
					var bytes : ByteArray = res.getBinary(true);
					var fileName : String = bytes.readUTF();
					var len : int = bytes.readUnsignedInt();				
					var fileBytes : ByteArray = new ByteArray();
					bytes.readBytes(fileBytes , 0 , len);
					content = XML(fileBytes.readUTFBytes(fileBytes.bytesAvailable));
				}catch(e : Error)
				{
					trace("bug == "+ e.toString() + e.getStackTrace());
				}
			}
			else
				content = ResourceManager.getInstance().bulkLoader.getXML(res.id, true);
			
			return content;
		}
		
		public static function getTxt(res : GameResource) : String
		{
			var content : *;
			if(res.getType() == BulkLoader.TYPE_BINARY)
			{
				var bytes : ByteArray = res.getBinary(true);
				var fileName : String = bytes.readUTF();
				var len : int = bytes.readUnsignedInt();				
				var fileBytes : ByteArray = new ByteArray();
				bytes.readBytes(fileBytes , 0 , len);
				content = fileBytes.readUTFBytes(fileBytes.bytesAvailable);
			}
			else
				content = ResourceManager.getInstance().bulkLoader.getText(res.id, true);

			return content;
		}
		
		public static function getBinary(res : GameResource , clearMomery : Boolean = false): ByteArray
		{
			var bytes : ByteArray = ResourceManager.getInstance().bulkLoader.getBinary(res.id ,clearMomery);
			if(res.attr['compress2crypt'])
			{
				try
				{
					bytes = ByteArrayUtil.decryptByteArray(bytes);
					bytes.uncompress();
				}catch(e : Error)
				{
					throw new Error("解压缩资源:" + res.id + "时发生错误:" + e.toString() + e.getStackTrace());
				}
			}
			return bytes;
		}
		
		public function ResourceParser()
		{
		}
	}
}